package com.ruoyi.warning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonParseException;
import com.ruoyi.common.enums.CommonString;
import com.ruoyi.warning.domain.entity.*;
import com.ruoyi.warning.domain.query.ConfigurationQuery;
import com.ruoyi.warning.domain.vo.ConfigurationVO;
import com.ruoyi.warning.mapper.ConfigurationMapper;
import com.ruoyi.warning.mapper.EventDetailMapper;
import com.ruoyi.warning.service.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 告警事件的详情表 服务实现类
 * </p>
 *
 * @author chenhc
 * @since 2025-05-20
 */
@Service
public class EventDetailServiceImpl extends ServiceImpl<EventDetailMapper, EventDetail> implements IEventDetailService {
    @Resource
    private IEventService eventService;
    @Resource
    private IDevicesService devicesService;
    @Resource
    private IConfigurationService configurationService;
    @Resource
    private IWarningConfigurationRuleRelationService relationService;
    @Resource
    private IDisposeService disposeService;
    @Resource
    private IPropertyService propertyService;
    @Resource
    private IPortsService portsService;
    @Resource
    private ConfigurationMapper configurationMapper;
    @Resource
    private HttpServletRequest request;

    // 获取客户端IP的方法
    public String getClientIp() {
        StringBuilder sb = new StringBuilder();
        String ipAddress = request.getHeader("X-Forwarded-For");
        if(ipAddress != null){
            sb.append("X-Forwarded-For:"+ipAddress);
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
            sb.append("Proxy-Client-IP:"+ipAddress);
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
            sb.append("WL-Proxy-Client-IP:"+ipAddress);
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            sb.append("RemoteAddr:"+ipAddress);
        }
//        return ipAddress;
        return sb.toString();
    }
//    @Override
//    public void receiveEventOld(Object obj) throws Exception {
//        try {
//        java.util.Map<String, String> map = com.alibaba.fastjson.JSON.parseObject(obj.toString(), java.util.Map.class);
//        Device device =
//                devicesService.getOne(
//                        new QueryWrapper<Device>().lambda()
//                                .eq(Device::getHostname,map.get("hostname")));
//        if (device == null) {
//            // 可根据实际情况处理设备不存在的情况，这里简单返回
//            return;
//        }
//        java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        java.time.LocalDateTime warningTime = java.time.LocalDateTime.parse(map.get("timestamp"), formatter);
//        // 解析 Rule 部分
//        String title = map.get("msg");
//        int ruleIndex = title.indexOf("Rule:");
//        if (ruleIndex != -1) {
//            int nextSemicolon = title.indexOf("Faults:", ruleIndex);
//            if (nextSemicolon != -1) {
//                title = title.substring(ruleIndex + "Rule:".length(), nextSemicolon).trim();
//            }else {
//                title = map.get("title");
//                if(title.contains("-")){
//                    title = title.split(" - ")[1];
//                    title = title.replace(" ","");
//                }
//            }
//        }
//
//        //先找到是否已存在该事件
//        LambdaQueryWrapper wrapper = new QueryWrapper<Event>().lambda()
//                .eq(Event::getDeviceId,device.getDeviceId())
//                .eq(Event::getWarningTime,warningTime)
//                .eq(Event::getTitle,title)
//                .orderByDesc(Event::getUpdateTime)
//                .last("limit 1");
//        Event event = eventService.getOne(wrapper);
//        //为时间间隔做准备
//        LocalDateTime lastDateTime = null;
//        ZoneId systemZone = ZoneId.systemDefault();
//        EventDetail eventDetail = new EventDetail();
//        if (!ObjectUtils.isEmpty(event)) {
//            lastDateTime = event.getUpdateTime().toInstant().atZone(systemZone).toLocalDateTime();
//            Dispose dispose =
//                    disposeService.getOne(
//                            new QueryWrapper<Dispose>().lambda()
//                                    .eq(Dispose::getEventId, event.getId()));
//            // 如果有就更新
//            if (!ObjectUtils.isEmpty(dispose)) {
//                if (dispose.getDisposeStatus().equals(CommonString.IGNORE.getCode())) {
//                    event.setRemark(CommonString.IGNORE.getCode());
//                    eventDetail.setIsWarning("0");
//                } else {
//                    event.setRemark(CommonString.INWARNING.getCode());
//                    eventDetail.setIsWarning("1");
//                }
//            } else {
//                event.setRemark(CommonString.INWARNING.getCode());
//                eventDetail.setIsWarning("0");
//            }
//        } else {
//            // 没有就新增，重新初始化 event 对象
//            Property property = propertyService.getOne(
//                    new QueryWrapper<Property>().lambda()
//                           .eq(Property::getHostname, map.get("hostname")));
//            event = new Event();
//            event.setDeviceId(device.getDeviceId());
//            event.setHostName(map.get("hostname"));
//            if(ObjectUtils.isNotEmpty(property)){
//                event.setDeviceName(property.getName());
//            }else {
//                event.setDeviceName(device.getSysName());
//            }
//            event.setWarningTime(warningTime);
//            event.setMsg(map.get("msg"));
//            event.setRemark("正在告警中");
//            event.setTitle(title);
//            eventDetail.setIsWarning("0");
//        }
//        //修改或新增事件
//        eventService.saveOrUpdate(event);
//        System.out.println("第一次保存");
//        //找到刚才的事件
//        event = eventService.getOne(wrapper);
//        //添加事件详情
//        eventDetail.setEventId(event.getId());
//        eventDetail.setMsg(event.getMsg());
//        eventDetail.setWarningTime(warningTime);
//        eventDetail.setTitle(title);
//        eventDetail.setRemark("正在告警中");
//        this.saveOrUpdate(eventDetail);
//        eventDetail = this.getOne(
//                new QueryWrapper<EventDetail>().lambda()
//                       .eq(EventDetail::getEventId,event.getId())
//                       .orderByDesc(EventDetail::getCreateTime)
//                       .last("limit 1"));
//        LambdaQueryWrapper<Configuration> configurationwrapper = new QueryWrapper<Configuration>().lambda()
//                .apply("FIND_IN_SET({0}, device_id)", event.getDeviceId())
//                // 按照创建时间降序排序
//                .eq(Configuration::getDelFlag,0)
//                .orderByDesc(Configuration::getCreateTime,Configuration::getWarningLevel)
//                ;
//
//        List<Configuration> list = configurationService.list(configurationwrapper);
//        if(ObjectUtils.isEmpty(list)){
//            event.setRemark("告警方式未配置");
//            eventDetail.setRemark("告警方式未配置");
//            eventService.saveOrUpdate(event);
//            this.saveOrUpdate(eventDetail);
//            System.out.println("第二次保存");
//            return;
//        }
//        //todo 之后要改成先找到对应的规则，然后在匹配对应的告警配置
//        Event finalEvent = event;
//        for(Configuration configuration:list){
//            List<WarningConfigurationRuleRelationVO> relationList = relationService.getRuleRelationList(configuration.getId());
//            EventDetail eventDetailWarning = this.getOne(
//                    new QueryWrapper<EventDetail>().lambda()
//                            .eq(EventDetail::getEventId,event.getId())
//                            .eq(EventDetail::getIsWarning,"1")
//                            .orderByDesc(EventDetail::getCreateTime)
//                            .last("limit 1"));
//            if(!ObjectUtils.isEmpty(eventDetailWarning)){
//                eventDetail = eventDetailWarning;
//            }
//            if(relationList.stream()
//                    .anyMatch(relation -> finalEvent.getTitle().equals(relation.getRuleName()))){
//                //离线检测和端口检测
//                if(finalEvent.getTitle().contains("离线")){
//                    // 获取设备的主机名
//                    String hostname = finalEvent.getHostName();
//                    try {
//                        // 根据不同操作系统构建不同的 ping 命令
//                        ProcessBuilder processBuilder;
//                        if (System.getProperty("os.name").toLowerCase().contains("win")) {
//                            // Windows 系统，ping 4 次
//                            processBuilder = new ProcessBuilder("cmd", "/c", "ping", "-n", "4", hostname);
//                        } else {
//                            // Linux 或 macOS 系统，ping 4 次
//                            processBuilder = new ProcessBuilder("ping", "-c", "4", hostname);
//                        }
//                        // 启动进程
//                        Process process = processBuilder.start();
//                        // 获取进程的退出值，0 表示成功
//                        int exitCode = process.waitFor();
//                        if (exitCode == 0) {
//                            event.setRemark(hostname + " 可访问 " + LocalDateTime.now());
//                        } else {
//                            event.setRemark(hostname + " 不可访问" + LocalDateTime.now());
//                        }
//                    } catch (Exception e) {
//                        System.err.println("执行 ping 命令时出错: " + e.getMessage());
//                    }
//                    //event.setRemark("告警完毕");
//                }else if(finalEvent.getTitle().contains("端口")){
//                    String portId = "未知";
//                    int portIndex = title.indexOf("port_id = ");
//                    if (portIndex != -1) {
//                        int nextSemicolon = title.indexOf("; ifDescr", portIndex);
//                        if (nextSemicolon != -1) {
//                            portId = title.substring(portIndex + "port_id = ".length(), nextSemicolon).trim();
//                            Port port = portsService.getOne(new LambdaQueryWrapper<Port>()
//                                    .eq(portId!= null,Port::getPortId,portId));
//                            finalEvent.setTitle(finalEvent.getTitle()+" 端口名称为："+port.getPortName());
//                        }
//                    }
//                }
//                //检查是否是首次告警
//                EventDetail firstWarningDetail = this.getOne(
//                        new QueryWrapper<EventDetail>().lambda()
//                                .eq(EventDetail::getEventId,event.getId())
//                                .eq(EventDetail::getIsWarning,"1")
//                                .orderByDesc(EventDetail::getCreateTime)
//                                .last("limit 1"));
//
//                //计算时间间隔（如果之前有过告警）
//                long minutes = 0;
//                boolean hasPreviousWarning = ObjectUtils.isNotEmpty(firstWarningDetail);
//                if(hasPreviousWarning){
//                    systemZone = ZoneId.systemDefault();
//                    LocalDateTime lastWarningTime = firstWarningDetail.getCreateTime().toInstant().atZone(systemZone).toLocalDateTime();
//                    Duration duration = Duration.between(lastWarningTime, LocalDateTime.now(systemZone));
//                    minutes = duration.toMinutes();
//                }
//
//                //如果没有之前的告警记录，则直接发送告警
//                if(ObjectUtils.isEmpty(firstWarningDetail)){
//                    event.setRemark("告警通知中。。。");
//                    event.setEventLevel(configuration.getWarningLevel());
//                    this.saveOrUpdate(eventDetail);
//                    eventDetail = this.getOne(
//                            new QueryWrapper<EventDetail>().lambda()
//                                    .eq(EventDetail::getEventId,event.getId())
//                                    .orderByDesc(EventDetail::getCreateTime)
//                                    .last("limit 1"));
//                    eventDetail.setIsWarning("1");
//                    event = configurationService.warningSend(event,eventDetail,configuration);
//                    System.out.println("直接告警");
//                    eventService.saveOrUpdate(event);
//                    eventDetail.setRemark(event.getRemark());
//                    if("1".equals(eventDetail.getIsWarning())){
//                        eventDetail.setRemark("已通知");
//                    }
//                    this.saveOrUpdate(eventDetail);
//                    System.out.println("最终保存");
//                    return;
//                }
//                System.out.println("===================================");
//                System.out.println(event.getWarningTime());
//                System.out.println(LocalDateTime.now());
//                System.out.println("===================================");
//
//                //超过设定时间以上的则发送告警
//                if(minutes > configuration.getTimeInterval()){
//                    event.setRemark("告警通知中。。。");
//                    event.setEventLevel(configuration.getWarningLevel());
//                    event.setIsWarning("1");
//                    eventDetail.setIsWarning("1");
//                    event = configurationService.warningSend(event,eventDetail,configuration);
//                    this.saveOrUpdate(eventDetail);
//                    System.out.println("第二次告警");
//                } else {
//                    eventDetail = this.getOne(
//                            new QueryWrapper<EventDetail>().lambda()
//                                    .eq(EventDetail::getEventId,event.getId())
//                                    .orderByDesc(EventDetail::getCreateTime)
//                                    .last("limit 1"));
//                    //不发送告警
//                    event.setRemark("时间间隔小于"+configuration.getTimeInterval()+"分钟，间隔时间为："+minutes);
//                    eventService.saveOrUpdate(event);
//                    eventDetail.setRemark(event.getRemark());
//                    eventDetail.setIsWarning("0");
//                    this.saveOrUpdate(eventDetail);
//                    System.out.println("第三次保存");
//                }
//                break;
//            }else {
//                eventDetail = this.getOne(
//                        new QueryWrapper<EventDetail>().lambda()
//                                .eq(EventDetail::getEventId,event.getId())
//                                .orderByDesc(EventDetail::getCreateTime)
//                                .last("limit 1"));
//                event.setRemark("告警方式未配置对应规则");
//                eventDetail.setIsWarning("0");
//                eventDetail.setRemark("告警方式未配置对应规则");
//            }
//        }
//        eventService.saveOrUpdate(event);
//        eventDetail.setRemark(event.getRemark());
//        if("1".equals(eventDetail.getIsWarning())){
//            eventDetail.setRemark("已通知");
//        }
//        this.saveOrUpdate(eventDetail);
//        System.out.println("最终保存");
//        } catch (JsonParseException e) {
//            System.out.println("=======================");
//            log.error("JSON解析错误，原始数据: {}",e);
//            System.out.println("JSON格式错误: " + e.getMessage());
//        }
//    }


    @Override
    public void receiveEvent(Object obj) throws Exception {
        //事件状态0待处理1不符合规则2符合规则3不是第一次报警4在时间间断内5进入报警6已被忽略7第一次报警
        int eventStatus = 0;
        try {

            //解析JSON数据
            java.util.Map<String, String> map = com.alibaba.fastjson.JSON.parseObject(obj.toString(), java.util.Map.class);
            Device device = devicesService.getOne(new QueryWrapper<Device>().lambda()
                                    .eq(Device::getHostname,map.get("hostname")));
            if (device == null) {
                // 可根据实际情况处理设备不存在的情况，这里简单返回
                return;
            }
            //找到告警时间
            java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            java.time.LocalDateTime warningTime = java.time.LocalDateTime.parse(map.get("timestamp"), formatter);
            // 解析 Rule 部分
            String title = map.get("msg");
            int ruleIndex = title.indexOf("Rule:");
            if (ruleIndex != -1) {
                int nextSemicolon = title.indexOf("Faults:", ruleIndex);
                if (nextSemicolon != -1) {
                    title = title.substring(ruleIndex + "Rule:".length(), nextSemicolon).trim();
                }else {
                    title = map.get("title");
                    if(title.contains("-")){
                        title = title.split(" - ")[1];
                        title = title.replace(" ","");
                    }
                }
            }

            ConfigurationVO configurationVO = this.getConfiguration(device,title);
            if(ObjectUtils.isEmpty(configurationVO)){
                //没找到配置
                eventStatus = 1;
            }

            //先找到是否已存在该事件
            LambdaQueryWrapper wrapper = new QueryWrapper<Event>().lambda()
                    .eq(Event::getDeviceId,device.getDeviceId())
                    //为了防止底座告警重复
                    .eq(Event::getWarningTime,warningTime)
                    .eq(Event::getTitle,title)
                    .likeRight(Event::getMsg,"Alert")
                    .orderByDesc(Event::getUpdateTime)
                    .last("limit 1");
            Event event = eventService.getOne(wrapper);
            EventDetail eventDetail = new EventDetail();
            eventDetail.setWarningTime(warningTime);
            eventDetail.setId(UUID.randomUUID().toString().replace("-", ""));
            eventDetail.setIsWarning("0");
            eventDetail.setMsg(map.get("msg"));
            eventDetail.setTitle(title);
            System.out.println("+++++++++++++++++++");
            System.out.println(eventDetail);
            long interval = 0;
            //event为空，则创建新事件，否则更新事件
            if (ObjectUtils.isEmpty(event)) {
                // 没有就新增，重新初始化 event 对象
                Property property = propertyService.getOne(
                        new QueryWrapper<Property>().lambda()
                                .eq(Property::getHostname, map.get("hostname")));
                event = new Event();
                event.setDeviceId(device.getDeviceId());
                event.setHostName(device.getHostname());
                if(ObjectUtils.isNotEmpty(property)){
                    event.setDeviceName(property.getName());
                }else {
                    event.setDeviceName(device.getSysName());
                }
                event.setWarningTime(warningTime);
                event.setTitle(title);
                event.setMsg(map.get("msg"));
                //如果告警方式未配置对应规则，直接告警失败
                if(eventStatus==1){
                    this.warningFail(event,eventDetail,eventStatus,null);
                    return;
                }
                event.setRemark("正在告警中");
                //第一次告警
                eventStatus = 7;
            }else {
                //事件不为空，查看上次事件的时间和当前时间间隔
                ZoneId systemZone = ZoneId.systemDefault();
                LocalDateTime lastWarningTime = event.getUpdateTime().toInstant().atZone(systemZone).toLocalDateTime();
                interval = Duration.between(lastWarningTime, warningTime).toMinutes();
                if(eventStatus==1){
                    this.warningFail(event,eventDetail,eventStatus,null);
                    return;
                }
                if(interval>configurationVO.getTimeInterval()){
                    eventStatus = 4;
                    this.warningFail(event,eventDetail,eventStatus,"未超出时间间隔："+configurationVO.getTimeInterval()+"分钟");
                    return;
                }
                //再看是否被忽略
                Dispose dispose =
                        disposeService.getOne(
                                new QueryWrapper<Dispose>().lambda()
                                        .eq(Dispose::getEventId, event.getId()));
                // 如果有就更新
                if (!ObjectUtils.isEmpty(dispose)) {
                    if (dispose.getDisposeStatus().equals(CommonString.IGNORE.getCode())) {
                        event.setRemark(CommonString.IGNORE.getCode());
                        eventDetail.setIsWarning("0");
                        //被忽略
                        eventStatus = 6;
                    } else {
                        event.setRemark(CommonString.INWARNING.getCode());
                        eventDetail.setIsWarning("1");
                    }
                } else {
                    event.setRemark(CommonString.INWARNING.getCode());
                    eventDetail.setIsWarning("0");
                }
            }
            //添加事件详情
            eventDetail.setRemark("正在告警中");
            eventDetail.setEventId(event.getId());
            eventDetail.setWarningTime(warningTime);
            if(eventStatus==6){
                this.warningFail(event,eventDetail,eventStatus,null);
                return;
            }
            //无论什么情况，都要保存一下事件
            if(ObjectUtils.isEmpty(event.getId())){
                String uuid = UUID.randomUUID().toString().replace("-", "");
                event.setId(uuid);
                eventDetail.setEventId(uuid);
            }
            eventService.saveOrUpdate(event);
            this.saveOrUpdate(eventDetail);
            //修改或新增事件
            System.out.println("第一次保存");

            //这是最新添加的事件详情
//            eventDetail = this.getOne(
//                    new QueryWrapper<EventDetail>().lambda()
//                            .eq(EventDetail::getEventId,event.getId())
//                            .orderByDesc(EventDetail::getCreateTime)
//                            .last("limit 1"));
            Event finalEvent = event;
            //特殊规则特殊处理一下
            event = specialRule(finalEvent,event,title);
            //已修复
            if(obj.toString().contains("recovered")){
                System.out.println(interval);
                wrapper = new QueryWrapper<Event>().lambda()
                        .eq(Event::getDeviceId,device.getDeviceId())
                        .eq(Event::getTitle,title)
                        .likeRight(Event::getMsg,"Alert")
                        .orderByDesc(Event::getUpdateTime)
                        .last("limit 1");
                Event lastEvent = eventService.getOne(wrapper);
                ZoneId systemZone = ZoneId.systemDefault();
                LocalDateTime lastWarningTime = lastEvent.getUpdateTime().toInstant().atZone(systemZone).toLocalDateTime();
                interval = Duration.between(lastWarningTime, warningTime).toMinutes();
                String time = formatInterval(interval);
                event.setTitle(event.getTitle()+"已修复,耗时"+time);
            }
            event = configurationService.warningSend(event,eventDetail,configurationVO);
            eventService.saveOrUpdate(event);
            eventDetail.setRemark(event.getRemark());
            if("1".equals(eventDetail.getIsWarning())){
                eventDetail.setRemark("已通知");
            }
            this.saveOrUpdate(eventDetail);
            System.out.println("最终保存");
        } catch (JsonParseException e) {
            System.out.println("=======================");
            log.error("JSON解析错误，原始数据: {}",e);
            System.out.println("JSON格式错误: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        ZoneId systemZone = ZoneId.systemDefault();
        java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        java.time.LocalDateTime warningTime = java.time.LocalDateTime.parse("2025-10-21 14:44:00", formatter);
        System.out.println(warningTime);
        Long minutes = Duration.between(LocalTime.now(), warningTime).toMinutes();
        System.out.println(minutes);
        if(minutes<0){
            minutes = minutes * -1;
        }
        long days = minutes / (24 * 60);
        long hours = (minutes % (24 * 60)) / 60;
        long mins = minutes % 60;

        StringBuilder sb = new StringBuilder();
        if (days > 0) {
            sb.append(days).append("天");
        }
        if (hours > 0) {
            sb.append(hours).append("小时");
        }
        if (mins > 0) {
            sb.append(mins).append("分钟");
        }
        System.out.println(sb);
    }

    private ConfigurationVO getConfiguration(Device device,String title) throws Exception {
        ConfigurationQuery query = new ConfigurationQuery();
        query.setDeviceId(device.getDeviceId().toString());
        query.setTitle(title);
        List<ConfigurationVO> list = configurationMapper.getList(query);
        if(ObjectUtils.isEmpty(list)){
            //没找到配置
            return null;
        }
        return list.get(0);
    }

    //各种各样的原因报警失败
    private void warningFail(Event event,
                             EventDetail eventDetail,
                             int eventStatus,
                             String remark
                             ) throws Exception {
        //事件状态0待处理1不符合规则2符合规则3不是第一次报警4在时间间断内5进入报警6已被忽略7第一次报警
        event.setIsWarning("0");
        eventDetail.setIsWarning("0");
        switch (eventStatus) {
            //不符合规则,保存事件和详情
            case 1:
                event.setRemark("未找到对应规则，取消报警");
                eventDetail.setRemark("未找到对应规则，取消报警");
                break;

            case 4:
                event.setRemark(remark);
                eventDetail.setRemark(remark);
                break;

            case 6:
                event.setRemark("该告警已被忽略");
                eventDetail.setRemark("该告警已被忽略");
                break;

            default:
                event.setRemark("未知告警失败");
                eventDetail.setRemark("未知告警失败");
                break;
        }
        if(ObjectUtils.isEmpty(event.getId())){
            String uuid = UUID.randomUUID().toString().replace("-", "");
            event.setId(uuid);
        }
        eventDetail.setEventId(event.getId());
        eventService.saveOrUpdate(event);
        this.saveOrUpdate(eventDetail);
    }


    //报警，保存，发送
    private void disposeEvent(Event event,
                              EventDetail eventDetail,
                              Configuration configuration,
                              int eventStatus) throws Exception {
        //事件状态0待处理1不符合规则2符合规则3不是第一次报警4在时间间断内5进入报警6已被忽略7第一次报警
        switch (eventStatus) {
            //不符合规则,保存事件和详情
            case 1:
                event.setIsWarning("0");
                eventDetail.setIsWarning("0");
                event.setRemark("不符合规则");
                eventDetail.setRemark("不符合规则，取消报警");
                eventService.saveOrUpdate(event);
                this.saveOrUpdate(eventDetail);
                break;
            //符合规则,保存事件和详情
            case 2:
                event.setRemark("符合规则");
                eventDetail.setRemark("符合规则");
                eventService.saveOrUpdate(event);
                this.saveOrUpdate(eventDetail);
                break;
            //不是第一次报警
            case 3:
                break;
            //在时间间断内
            case 4:
                event.setIsWarning("0");
                eventDetail.setIsWarning("0");
                event.setRemark("在时间间断内");
                eventDetail.setRemark("在时间间断内");
                eventService.saveOrUpdate(event);
                this.saveOrUpdate(eventDetail);
                break;
            //进入报警
            case 5:
                break;
            //已被忽略
            case 6:
                event.setIsWarning("0");
                event.setRemark("已被忽略");
                eventDetail.setIsWarning("0");
                eventDetail.setRemark("已被忽略");
                eventService.saveOrUpdate(event);
                this.saveOrUpdate(eventDetail);
                break;
            //第一次报警
            case 7:

                break;
            //默认情况下就简单保存
            default:

                eventService.saveOrUpdate(event);
                this.saveOrUpdate(eventDetail);
                break;
        }
    }
    //特殊规则额外处理
    private Event specialRule(Event finalEvent,Event event,String title) throws Exception {
        if(finalEvent.getTitle().contains("离线")){
            // 获取设备的主机名
            String hostname = finalEvent.getHostName();
            try {
                // 根据不同操作系统构建不同的 ping 命令
                ProcessBuilder processBuilder;
                if (System.getProperty("os.name").toLowerCase().contains("win")) {
                    // Windows 系统，ping 4 次
                    processBuilder = new ProcessBuilder("cmd", "/c", "ping", "-n", "4", hostname);
                } else {
                    // Linux 或 macOS 系统，ping 4 次
                    processBuilder = new ProcessBuilder("ping", "-c", "4", hostname);
                }
                // 启动进程
                Process process = processBuilder.start();
                // 获取进程的退出值，0 表示成功
                int exitCode = process.waitFor();
                if (exitCode == 0) {
                    event.setRemark(hostname + " 可访问 " + LocalDateTime.now());
                } else {
                    event.setRemark(hostname + " 不可访问" + LocalDateTime.now());
                }
            } catch (Exception e) {
                System.err.println("执行 ping 命令时出错: " + e.getMessage());
            }
            //event.setRemark("告警完毕");
        }
        else if(finalEvent.getTitle().contains("端口")){
            String portId;
            int portIndex = title.indexOf("port_id = ");
            if (portIndex != -1) {
                int nextSemicolon = title.indexOf("; ifDescr", portIndex);
                if (nextSemicolon != -1) {
                    portId = title.substring(portIndex + "port_id = ".length(), nextSemicolon).trim();
                    Port port = portsService.getOne(new LambdaQueryWrapper<Port>()
                            .eq(portId!= null,Port::getPortId,portId));
                    event.setTitle(event.getTitle()+" 端口名称为："+port.getPortName());
                }
            }
        }
        return event;
    }

    public static String formatInterval(long minutes) {
        if(minutes<0){
            minutes = minutes * -1;
        }
        long days = minutes / (24 * 60);
        long hours = (minutes % (24 * 60)) / 60;
        long mins = minutes % 60;

        StringBuilder sb = new StringBuilder();
        if (days > 0) {
            sb.append(days).append("天");
        }
        if (hours > 0) {
            sb.append(hours).append("小时");
        }
        if (mins > 0) {
            sb.append(mins).append("分钟");
        }
        return sb.toString();
    }
}
